import React from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter,Link } from 'react-router-dom';
import * as mobx from 'mobx';
import objectAssign from 'object-assign';
import { Browser,BrowserHrm,BrowserCity,BrowserLeave,BrowserHrmCondition } from 'weaver-mobile-page';
import * as API_REQ from '../../apis/form';
import WfDateTime from '../../public/wf-form-datetime/index';
import WfSelect from '../../public/wf-form-select/index';
import WfChooseItem from '../../public/wf-choose-item/index';
import * as Common from '../../util/common';
import { _, FieldUtil } from '../../util/pcPublic';
import * as emSDK from './../../util/emSDK'
import  * as FormUtil from './../../util/formUtil'
const { getValueWrap } = Browser;

@inject('wfGlobalStore', 'wfLayoutStore','wfOperateStore')
@withRouter
@observer
export default class BrowserElement extends React.Component{
    doChangeEvent(value){
        console.log("doChangeEvent",value);
        const { fieldMark,wfLayoutStore } = this.props;
		wfLayoutStore.changeSingleFieldValue(fieldMark, {value: value});
	}
    doBrowChangeEvent(ids, names, datas, rowDatas){
        const valueArray = mobx.toJS(datas) || [];
        console.log("ids",ids,"names",names,"datas",datas,valueArray); 
        const valueInfo = { value: ids || '', specialobj: valueArray};
        const { fieldid,fieldMark,rowIndex,fieldAttr,detailtype,wfLayoutStore,wfGlobalStore } = this.props;
        const { requestid } = wfGlobalStore.commonParam;
        const { isDetail,fielddbtype } = fieldAttr;
        let variable = {};
        if(detailtype === 226){     //SAP浏览按钮
            let sapParams = {fromNodeorReport:"0", fieldid,rowIndex,requestid,fielddbtype};
            sapParams["datas"] = JSON.stringify(rowDatas);
            API_REQ.convertSapDatas(sapParams).then(result =>{
                let changeDatas = {};
                result.datas && result.datas.map(item =>{
                    changeDatas = {...changeDatas, ...item};
                });
                wfLayoutStore.changeMoreFieldData(changeDatas);
            });
            return;
        }
        if(detailtype === 141){     //人力资源条件值转换
            valueInfo.value = FieldUtil.spellResourceCondition(datas);
        }
        wfLayoutStore.changeSingleFieldValue(fieldMark, valueInfo, variable);
        //触发浏览按钮变更事件
		// formUtil.doDefinitionCallBackFun(fieldid, rowIndex, ids, datas, fieldAttr);
    }
    doSignFiles(item, odocInfo, showname, viewAttr, isannexupload_edit, e) {
        emSDK.confirmSignType(odocInfo.imagefileId, item.id, showname, viewAttr, isannexupload_edit);//odocInfo.imagefileId附件id，item.id文档ID
        e.stopPropagation();
    }
    render() {
        const { fieldid,fieldMark,detailtype,viewAttr,fieldAttr,symbol,rowIndex,cellObj,fieldObj,wfLayoutStore,wfGlobalStore } = this.props;
        const { commonParam } = wfGlobalStore;
        const { isviewonly,appDetachDisableAll, useInvoiceCloud=false } = commonParam;
        const { odocInfo } = wfLayoutStore;
        const { isDetail, fielddbtype } = fieldAttr;
        const { markInfo = {},variableMap } = this.props.wfOperateStore;
        const { isannexupload_edit = false } = markInfo;
        let { specialobj,variable } = fieldObj;
        let value = this.props.fieldValue;
        const valueArray  = specialobj ? mobx.toJS(specialobj) : [];
        let browserProp  = this.getBrowserProp(detailtype, fielddbtype);
        browserProp.type = detailtype;
        browserProp.viewAttr = viewAttr;
        browserProp.value = value;
        browserProp.valueArray = valueArray;
        this.extendBrowserProp(browserProp, fieldid, isDetail, detailtype);
        let mobileWFOffice = variableMap.has("mobileWFOffice") ? variableMap.get("mobileWFOffice") : "0";
        let el;
        if(detailtype === 2 || detailtype === 19 || detailtype === 290){      //日期时间
            if(detailtype === 19)
                value = FieldUtil.convertTimeValue(value);  //时间值补零
            let format = cellObj.format || {};
            let pickerProps = {};
            if(detailtype === 2){
                pickerProps.minDate = variable.get("startDate") || "";
                pickerProps.maxDate = variable.get("endDate") || "";
            }
            return (
                <WfDateTime
                    domKey={fieldMark}
                    detailtype={detailtype}
                    className="wf-req-datetime-item"
                    viewAttr={viewAttr}
                    value={value}
                    format={format}
                    onChange={this.doChangeEvent.bind(this)}
                    pickerProps={pickerProps}
                    fieldAttr={fieldAttr}
                />
            )
        }else if(detailtype === 34){    //请假类型
            let leaveOptions = [];
            if(!variable.has("leaveOptions")){
                //仅执行一次初始化取请假类型值
                API_REQ.getLeaveBrowserOptions(browserProp.dataParams).then(result =>{
                    const datas = result.datas;
                    datas && datas.map(item =>{
                        leaveOptions.push({value:item.key, label:item.showname});
                    });
                    fieldObj.changeVariable({leaveOptions});
                });
            }else{
                leaveOptions = variable.get("leaveOptions");
            }
            return (
                <WfSelect
                    domKey={fieldMark}
                    className="wf-req-select-item"
                    viewAttr={viewAttr}
                    value={value}
                    options={leaveOptions}
                    onChange={this.doChangeEvent.bind(this)}
                    fieldAttr={fieldAttr}
                />
            )
        }else if(detailtype === 118){   //会议室使用情况
            el =  (
                <div>
                    <span className="wf-meeting-roomplan" onClick={this.doShowLink.bind(this, "/spa/meeting/static4mobile/index.html#/roomplan")}>{Common.getLabel(15881,'会议室使用情况')}</span>
                    <input type='hidden' id={fieldMark} name={fieldMark} value={value}/>
                </div>
            )
        }else{
            const store = fieldObj.fieldStore;
            const supportLink = this.judgeSupportLink(detailtype);
            let showValue = [];
            valueArray && valueArray.map((item,index) =>{
                let isHrmGroup = detailtype === 17 && item.type != "resource";
                let showname = item.name || item.lastname;
                if(detailtype === 17 && item.type !== "resource" && item.users)
                    showname = `${showname}(${item.users.length})`;
                if(detailtype === 141)     //人力资源条件
                    showname = store.getValueSpan(item, browserProp.isShowSecLevel);
                let valueWrap = getValueWrap(browserProp);
                valueWrap && index > 0 ? showValue.push(<br />) : "";
                showValue.push(<span key={`showitem_${index}`}
                    className={`wf-field-show-item ${(supportLink && !isHrmGroup) ? "wf-field-show-item-link":""}`}
                    dangerouslySetInnerHTML={{__html:showname}}
                    onClick={this.doClickShowItem.bind(this, item, detailtype)} />);
                if (mobileWFOffice == 1 && isviewonly != 1 && this.getSignCondition(viewAttr, detailtype, odocInfo, fieldid, item.id)){
                    showValue.push(<br/>);
                    showValue.push(<span className="wf-document-qp" onClick={this.doSignFiles.bind(this, item, odocInfo, showname + odocInfo.extendName, viewAttr, isannexupload_edit)}>
                    {(odocInfo.extendName.split(".")[1] == "pdf" || odocInfo.extendName.split(".")[1] == "PDF") ? Common.getLabel(504662, "PDF签批"):Common.getLabel(504344,"正文签批")}
                </span>) 
                }
                    
            });
            let clickEvent;
            if(viewAttr > 1){
                if(useInvoiceCloud === true &&( detailtype===292 || detailtype=== 293)){
                    clickEvent=()=>{
                        const {invoiceCloudInfo={}} = this.props.wfGlobalStore;
                        if(!invoiceCloudInfo.token)return;
                        let valueobj = this.getECID_FID();
                        wfGlobalStore.setInvoiceCloudInfo({fieldMark,detailtype,checked:valueobj.cloudId});
                        this.props.history.push("/req/InvoicePage");
                    }
                }else{
                    clickEvent = ()=>{this.props.history.push(store.path)};
                }
            }
            let extraElement;
            if(detailtype === 87 || detailtype === 184)
                extraElement = <div className="wf-meeting-roomplan" onClick={this.doShowLink.bind(this, "/spa/meeting/static4mobile/index.html#/roomPlan?src=workflow")}>{Common.getLabel(15881,'会议室使用情况')}</div>;
            let isShowRightIcon = true;
            if((detailtype === 9 || detailtype === 37) && "docFieldId" in odocInfo && odocInfo.docFieldId.toString() === fieldid && odocInfo.newTextNodes===true)
                isShowRightIcon=false;
            const showComp = (
                <WfChooseItem
                    key={`show_${fieldMark}`}
                    domKey={fieldMark}
                    className="wf-req-browser-item"
                    realValue={value}
                    showValue={showValue}
                    viewAttr={viewAttr}
                    onClick={isShowRightIcon && viewAttr > 1 ? clickEvent : null}
                    extraElement={extraElement}
                    isShowRightIcon={isShowRightIcon}
                />
            );

            let BrowserCompProps = {id:fieldMark, key:`browser_${fieldMark}`, store:store, onChange:this.doBrowChangeEvent.bind(this)};
            BrowserCompProps = { ...browserProp, ...BrowserCompProps };
            let BrowserComp = null;
            if(detailtype === 1 || detailtype === 17){      //人力资源相关
                BrowserComp = <BrowserHrm {...BrowserCompProps}><span /></BrowserHrm>;
            }else if(detailtype === 141){   //人力资源条件
                BrowserComp = <BrowserHrmCondition {...BrowserCompProps} appDetachDisableAll={appDetachDisableAll}><span /></BrowserHrmCondition>;
            }else if(detailtype === 258 || detailtype === 263 || detailtype === 58 || detailtype === 2222 ){    //国家、城市、区县
                BrowserComp = <BrowserCity {...BrowserCompProps}><span /></BrowserCity>
            }else{
                BrowserComp = <Browser {...BrowserCompProps}><span /></Browser>;
            }
            return viewAttr > 1 ? [showComp, BrowserComp] : showComp;
        }
        return el == null ? <span>{Common.getLabel(500328,"暂不支持")}</span> : el;
    }

    getECID_FID=()=>{
        let {  fieldObj } = this.props;
        let specialobj  = fieldObj.specialobj ? mobx.toJS(fieldObj.specialobj) : [];
        let ecid=[];
        let cloudId=[];
        if(specialobj.length>0){
            specialobj.map(item=>{
                if(item.prop && item.prop.cloudId){
                    cloudId.push(item.prop.cloudId)
                }
                if(item.id){
                    ecid.push(item.id)
                }
            })
        }
        return {
            ecid:ecid,
            cloudId:cloudId
        }
    }
    
    getSignCondition = (viewAttr, detailtype, odocInfo, fieldid, itemid) => {
        const { markInfo = {} } = this.props.wfOperateStore;
        const { isannexupload_edit = false } = markInfo;
        return (detailtype === 9 || detailtype === 37) && "docFieldId" in odocInfo && odocInfo.docFieldId.toString() === fieldid && odocInfo.docParam.docid == itemid && odocInfo.extendName &&
            emSDK.checkSigningBatch(odocInfo.docParam.isEdit, odocInfo.extendName) && emSDK.checkShowSignBtn(odocInfo.extendName,viewAttr,isannexupload_edit)
    }
    //获取浏览框相关的表单字段值
    getBrowserProp(detailtype, fielddbtype){
        const { rowIndex,wfLayoutStore } = this.props;
        const isCusBrow = (detailtype === 161 || detailtype ===162 || detailtype === 256 || detailtype === 257);
        const browKey = isCusBrow ? detailtype +"_"+fielddbtype : detailtype.toString();
        const { browserInfo,fieldAttrMap } = wfLayoutStore;
        let browProp = _.cloneDeep(browserInfo[browKey] || {});
        if(_.isEmpty(browProp))
            return browProp;

        let relateFieldValue = {};
        browProp.relateFieldid && browProp.relateFieldid.map(field =>{
            const fieldid = field.split("_")[0];
            const isDetail = field.split("_")[1] === "1";
            const fieldAttr = fieldAttrMap.get(fieldid);
            let key = fieldAttr.fieldname;
            if(key){
                if(isDetail)
                    key = fieldAttr.tableName+"_"+key;
                if(isCusBrow)   //避免自定义浏览框依赖字段fieldname与其它参数重复
                    key = `${key.toLowerCase()}_${_.get(browProp, ["dataParams","currenttime"])}`;
                relateFieldValue[key] = FieldUtil.getRelateFieldValue(fieldid, rowIndex);
            }
        });
        let dataParams = browProp.dataParams || {};
        dataParams = {...dataParams, ...relateFieldValue};
        browProp.dataParams = dataParams;
        return browProp;
    }
    //浏览数据定义获取表单字段数据
    getBrowserDataDefinition(relateFields, detailtype){
        const { rowIndex,wfLayoutStore } = this.props;
    	let relateFieldValue = {};
        relateFields.map(field=>{
            const fieldid = field.split("_")[0];
            if(detailtype === 161 || detailtype === 162){
            }else{
                relateFieldValue[`field${fieldid}`] = FieldUtil.getRelateFieldValue(fieldid, rowIndex);
            }
        });
        relateFieldValue = {...relateFieldValue, ...FieldUtil.getRelateFieldShowName(relateFields, rowIndex)};
    	return relateFieldValue;
    }
    //设置浏览框表单参数
    extendBrowserProp(browserProp, fieldid, isDetail, detailtype){
        const { fieldValue,viewAttr,fieldAttr,fieldObj,rowIndex,wfGlobalStore } = this.props;
        const { fielddbtype,browserattr={} } = fieldAttr;
        const { relateFieldid,sqlWhereField,browserParams = {} } = browserattr;
        const {tabs = []} = browserParams;
        if(tabs.length > 0) {
            browserProp.tabs = mobx.toJS(tabs);
        }
        //delete browserParams.tabs;
        const { variable } = fieldObj;
        const { commonParam, secLevelInfo } = wfGlobalStore;
        const { requestid,workflowid,formid,isbill,f_weaver_belongto_userid,f_weaver_belongto_usertype,creater} = commonParam;
        if(detailtype === 17 && !isDetail){
        	browserProp.hasAddGroup = true;
        }
        if(detailtype === 1 || detailtype === 17){
        	browserProp.isShowGroup = !isDetail;
        }
        if(detailtype === 141){
            browserProp.isShowSecLevel = browserParams.isShowSecLevel;
        }
        if(detailtype === 226){     //SAP浏览按钮
            browserProp.sap = true;
        }
        //设置文档浏览框添加按钮及公文浏览框条件
        const isWorkflowDoc = commonParam.isWorkflowDoc || false;
        const flowDocFieldId = commonParam.flowDocFieldId || 0;
        if(viewAttr > 1 && detailtype === 9 && !isDetail && isWorkflowDoc && flowDocFieldId == fieldid) {
            if(_.trim(fieldValue).length === 0)
                browserProp.hasAddBtn = true;       //正文添加按钮
            browserProp.dataParams.isWord  = "1";
        }
        if(viewAttr > 1 && detailtype === 37) {
            browserProp.hasAddBtn = true;
        }
        //请求接口参数相关扩展
      	let tempConditionDataParams = browserProp.conditionDataParams || {};
        let dataParams = browserProp.dataParams || {};
      	let relateFieldDatas = relateFieldid ? this.getBrowserDataDefinition(relateFieldid, detailtype) :{};
      	let completeParams = browserProp.completeParams || {}

        let customDataParam = variable.has("customDataParam") ? variable.get("customDataParam") : {};
      	let reqinfo = {
            wfid: workflowid,
            billid: formid,
            isbill: isbill,
            requestid: requestid,
            f_weaver_belongto_userid: f_weaver_belongto_userid,
            f_weaver_belongto_usertype: f_weaver_belongto_usertype,
            wf_isagent: commonParam.isagent,
            wf_beagenter: commonParam.beagenter,
            fieldid: fieldid,
            viewtype: isDetail ? "1" : "0",
            fromModule: "workflow",
            wfCreater:creater
        };
        if(detailtype === 226){     //SAP浏览按钮
            reqinfo = {...reqinfo, ...{fielddbtype, rowIndex}};
        }
      	const browParams  = objectAssign({}, tempConditionDataParams,completeParams,dataParams, reqinfo, browserParams,relateFieldDatas,customDataParam);
        if(secLevelInfo && secLevelInfo.isOpenSec == true) {
            browParams.secretLevel = secLevelInfo.secLevel;
        }
        browserProp.conditionDataParams = browParams;
        browserProp.completeParams = browParams;
        browserProp.dataParams = browParams;
        browserProp.destDataParams = {...browserProp.destDataParams||{},...browParams, ...{fromModule: "workflow"}};

        if(detailtype === 16 || detailtype === 152 || detailtype === 171)
        	browserProp.linkUrl = `${browserProp.linkUrl}&fieldid=${fieldid}&requestid=`;
        //前端自定义浏览框属性覆盖
        let customBrowserProp = variable.has("customBrowserProp") ? variable.get("customBrowserProp") : {};
        for(let key in customBrowserProp){
            browserProp[key] = customBrowserProp[key];
        }
    }
    getLinkUrl(detailtype){
        const { wfLayoutStore,fieldAttr } = this.props;
        const { fielddbtype } = fieldAttr;
        const isCusBrow = (detailtype === 161 || detailtype ===162 || detailtype === 256 || detailtype === 257);
        const browKey = isCusBrow ? detailtype +"_"+fielddbtype : detailtype.toString();
        const { browserInfo } = wfLayoutStore;
        const browserObj = browserInfo[browKey] || {};
        return browserObj.linkUrl || "";
    }
    isRequestBrowser(detailtype){
        return detailtype === 16 || detailtype === 152 || detailtype === 171;
    }
    isDocBrowser(detailtype){
        return detailtype ===9 || detailtype === 37;
    }
    judgeSupportLink(detailtype){
        return this.isRequestBrowser(detailtype) || this.isDocBrowser(detailtype) || this.getLinkUrl(detailtype) !== "";
    }
    doClickShowItem(item, detailtype, e) {
        if(!this.judgeSupportLink(detailtype))
            return;
        //人力资源分组不能点击
        if(detailtype == 17 && item.type != "resource") {
            return;
        }
        const { wfLayoutStore,fieldid,isDetailShow,fieldAttr,wfGlobalStore } = this.props;
        const { isDetail } = fieldAttr;
        const baseRoute = isDetail && !isDetailShow ? "/req/editDetailRow" : "/req";
        //公文点击跳转单独处理
        const { odocInfo={} } = wfLayoutStore;
        if((detailtype === 9 || detailtype === 37) && "docFieldId" in odocInfo && odocInfo.docFieldId.toString() === fieldid && odocInfo.docParam.docid == item.id){
            const { mobileInfo={}, imagefileId, extendName}=odocInfo;
            const { isDownload } = mobileInfo;
            if(isDownload === true){
                const {variableMap}=wfGlobalStore;
                //签批后要用新的imagefileId
                const _imagefileId = (variableMap.has(`imagefiledId_${imagefileId}`) && (extendName != "pdf" || extendName!= "PDF")) ? variableMap.get(`imagefiledId_${imagefileId}`) : imagefileId;
                window.WfForm.downLoadFile(_imagefileId, baseRoute);
            }else{
                const {setTabKey,tabKey}=wfGlobalStore;
                const nowTabKey = tabKey;
                setTabKey("odoc")
                FormUtil.tabChangTriggerEvent("odoc",nowTabKey);
            }    
            e.stopPropagation();
            return;
        }
        if (this.isRequestBrowser(detailtype)) {
            Common.showFormReq(item.id, {}, baseRoute);
        } else if (this.isDocBrowser(detailtype)) {
            Common.showFormDoc(item.id, {}, baseRoute);
        } else {
            let linkurl = this.getLinkUrl(detailtype) || "";
            linkurl = linkurl.replace("~~~itemKeyHolder~~~", item.id);
            Common.showModulePage(linkurl, {}, baseRoute);
        }
        e.stopPropagation();
    }
    doShowLink(url,e){
        const { isDetailShow,fieldAttr } = this.props;
        const { isDetail } = fieldAttr;
        const baseRoute = isDetail && !isDetailShow ? "/req/editDetailRow" : "/req";
        Common.showHoverWindow(url, baseRoute);
        e.stopPropagation();
    }
}
